﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;

//常见错误举例：

//405错误：本错误为获取的本地文件路径出现问题或是在远程机不具备写入权限
//解决办法：检测文件路径，配置远程服务器中该文件具有写入权限（文件系统跟IIS服务器）

//409错误：本错误为远程服务器中不具备此目录
//解决办法：在远程机子中新建相应目录即可。


namespace Com.SoundVideo
{
    /// <summary>
    /// C# 上传文件至远程服务器（适用于桌面程序及web程序）
    /// 注意：我们配置的服务器的根目录必须在文件系统中具有写入权限，并且在IIS中的配置具有写入权限。
    ///<code>
    ///   //上传文件
    ///   //得到文件名，文件扩展名，服务器路径
    ///      string filePath = ""; //需要上传的文件，在这里可以根据需要采用OpenFileDialog来获取文件
    ///      string server = @"http://218.95.4.4/";   //上传路径
    ///     //创建webclient实例
    ///     WebClient myWebClient = new WebClient();
    ///    try{//使用Uploadfile方法上传
    ///             MyUpLoadFile.UpLoadFile(filePath, server, true);
    ///             MessageBox.Show("上传成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    ///         }catch (Exception ex){
    ///             MessageBox.Show(ex.Message);
    ///             return;
    ///         }
    /// </code>
    /// </summary>
    public class MyUpLoadFile
    {
         /// <summary>   
        /// WebClient上传文件至服务器，默认不自动改名   
        /// </summary>   
        /// <param name="fileNamePath">文件名，全路径格式</param>   
        /// <param name="urlString">服务器文件夹路径</param>   
        public static void UpLoadFile(string fileNamePath,string urlString)
        {   
            UpLoadFile(fileNamePath,urlString,false);   
        }
       /// <summary>   
        /// WebClient上传文件至服务器   
        /// </summary>   
        ///  <param name="fileNamePath">文件名，全路径格式</param>   
        /// <param name="urlString">服务器文件夹路径</param>   
        /// <param name="IsAutoRename">是否自动按照时间重命名</param>   
        public static void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
        {   
            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\")+1);   
            string newFileName = fileName;   
            if (IsAutoRename){   
               newFileName = DateTime.Now.ToString("yyMMddhhmmss")+DateTime.Now.Millisecond.ToString()+fileNamePath.Substring(fileNamePath.LastIndexOf("."));   
            }   
            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".")+1);   
            if (uriString.EndsWith("/")==false) uriString = uriString + "/";   
            uriString = uriString + newFileName;   
            WebClient myWebClient = new WebClient();   
            //设置应用程序的系统凭据   
            myWebClient.Credentials = CredentialCache.DefaultCredentials;   
            //要上传的文件穿件文件流   
            FileStream fs = new FileStream(fileNamePath,FileMode.Open,FileAccess.ReadWrite);   
            //以二进制方式读取   
            BinaryReader br = new BinaryReader(fs);   
            //当前流写入二进制   
            byte[] postArray = br.ReadBytes((int)fs.Length);   
            //打开流以二进制方式写入指定资源   
            Stream postStream = myWebClient.OpenWrite(uriString,"PUT");   
            try  
            {   
                if (postStream.CanWrite)   
                {   
                    postStream.Write(postArray, 0, postArray.Length);   
                    postStream.Close();   
                    fs.Dispose();   
                 // MessageBox.Show("上传成功");   
                }else{   
                    postStream.Close();   
                    fs.Dispose();   
                 // MessageBox.Show("上传失败");   
                }   
            }   
            catch (Exception ex)   
            {   
                postStream.Close();   
                fs.Dispose();   
                // MessageBox.Show("上传文件异常" + ex.Message);   
                throw ex;   
            }   
            finally    
            {   
                postStream.Close();   
                fs.Dispose();   
            }   
        }  
        /// <summary>   
        /// 下载服务器文件至客户端    
        /// </summary>   
        /// <param name="URL">被下载的文件地址，绝对路径</param>   
        /// <param name="Dir">另存放的目录</param>   
        public static void DownLoad(string URL, string Dir)
        {   
            WebClient client = new WebClient();   
            string fileName = URL.Substring(URL.LastIndexOf("\\")+1);//被下载的文件名   
            string Path = Dir + fileName;//另存为的绝对路径+文件名   
            try  
            {   
                WebRequest myRe = WebRequest.Create(URL);   
            }   
            catch (Exception ex)   
            {   
                MessageBox.Show("下载文件异常"+ex.Message);   
            }   
            try  
            {   
                client.DownloadFile(URL, fileName);   
                FileStream fs = new FileStream(fileName,FileMode.Open,FileAccess.Read);   
                BinaryReader br = new BinaryReader(fs);   
                byte[] mybyte = br.ReadBytes((int)fs.Length);   
                FileStream fstm = new FileStream(Path,FileMode.Create,FileAccess.Write);   
                fstm.Write(mybyte,0,(int)fs.Length);   
                fstm.Close();   
                MessageBox.Show("下载文件成功！");   
            }   
            catch (Exception ex)   
            {   
  
                MessageBox.Show("下载文件异常"+ex.Message);   
            }   
        }      
    }
}
